package com.zp.kidshop.common.interceptor;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.zp.kidshop.common.pojo.SysProp;
import com.zp.kidshop.common.util.LogUtil;


/**
 * 
 * @Title: ExceptionControllerLogInterceptor.java
 * @Package com.minghang.common.interceptor 
 * @Description: 拦截器，用于日志，和参数检查
 * @author 张鹏  
 * @date 2017年2月16日 下午3:06:35 
 * @version V1.0
 */
public class ExceptionControllerLogInterceptor extends HandlerInterceptorAdapter{
	
	
	@Override
	public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
//        log.debug("请求返回的ModelAndView: "+modelAndView);
        super.postHandle(request, response, handler, modelAndView);
    }
    //此处拦截所有参数，并且打印
	@Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
    	Map<String, String> paramMap = getParam(request);
		
		LogUtil.addLog("[Controller123-hibernate]:".concat(request.getRequestURI()));
		LogUtil.addLog("[Invok Time  ]:"+SysProp.getThisTime());
		if(paramMap == null){
			LogUtil.addLog("[Invok param ]:".concat("没有参数传入"));
		}else{
			LogUtil.addLog("[Invok param ]:".concat(paramMap.toString()));
		}
        return super.preHandle(request, response, handler);
    }

    
    /**获取参数---转MAP
	 * @throws IOException 
	 * @throws Exception */
	private Map<String, String> getParam(HttpServletRequest request) throws IOException {

		Map<String, String> paramMap = new HashMap<String,String>();                         // 装入左右入参Map
		String attName = null;                                       // Uri参数名称
		Object attVal  = null;                                       // Uri参数值
		
		Enumeration<String> enu = request.getParameterNames();       // 读取Uri中的param名称
		if(enu.hasMoreElements()){
			while (enu.hasMoreElements()) {                              // 有值则循环
				attName = enu.nextElement();                             // 取出param名称
				attVal  = request.getParameter(attName);                 // 取出param值
				paramMap.put(attName, (String)attVal);
			}
		}
//		else{
//			String data = GetRequestJsonUtils.getRequestJsonString(request);
//			paramMap = desDecrypt(data);
//		}
		return paramMap;
	}
	
}
